import csv
import time
import requests
from fake_useragent import UserAgent


def bv_to_av(bv):
    XOR_CODE = 23442827791579
    MASK_CODE = 2251799813685247
    MAX_AID = 1 << 51
    ALPHABET = "FcwAPNKTMug3GV5Lj7EJnHpWsx4tb8haYeviqBz6rkCy12mUSDQX9RdoZf"
    ENCODE_MAP = 8, 7, 0, 5, 1, 3, 2, 4, 6
    DECODE_MAP = tuple(reversed(ENCODE_MAP))

    BASE = len(ALPHABET)
    PREFIX = "BV1"
    PREFIX_LEN = len(PREFIX)
    CODE_LEN = len(ENCODE_MAP)

    def _bv2av(bvid: str) -> int:
        assert bvid[:3] == PREFIX

        bvid = bvid[3:]
        tmp = 0
        for i in range(CODE_LEN):
            idx = ALPHABET.index(bvid[DECODE_MAP[i]])
            tmp = tmp * BASE + idx
        return (tmp & MASK_CODE) ^ XOR_CODE

    def get_av(bv):
        return _bv2av(bv)

    return get_av(bv)




def pinglun(bv):
    ua = UserAgent(os='Windows')
    header = {
        'Cookie': "SESSDATA=3cfd6f47%2C1762365432%2Ce42d4%2A52CjCOG_eWtJacRQKLM7GYAIe5eh6qVKOkiTQTvuInXe6NIDJLj1AkoQODssvGK36dshUSVnBjZWVaR01kTFE4cC1ObEs2VVAxbU16aUFsejFaUXU1VW1fZHBpZGdSVFhvQWF6bWJ3UTUxOE1Pa3FuQUVKSm1hU1JkTDRSajlzMXhuY0dMNF90M1hRIIEC",
        'Accept': 'application/json, text/plain, */*',
        'Origin': 'https://www.bilibili.com',
        'Host': 'api.bilibili.com',
        'User-Agent': ua.random,
        'Accept-Language': 'zh-cn',
        'Connection': 'keep-alive'
        # 'cookie': "buvid3=77DBAFF5-7713-099E-0FB6-5169AF8F3A5187511infoc; b_nut=1733801987; _uuid=E7B15865-81110-52C8-1056E-E6BE910210B5CA88603infoc; buvid4=A7453AB9-F961-93D0-810B-253C13FD0A4689540-024121003-MheELjODzs5aV6Hi2NNVIQ%3D%3D; rpdid=|(k|~RuRuR~u0J'u~JJ)|ummu; header_theme_version=CLOSE; enable_web_push=DISABLE; DedeUserID=19312722; DedeUserID__ckMd5=050b617edeb729c7; LIVE_BUVID=AUTO7617404828438310; hit-dyn-v2=1; PVID=7; fingerprint=0921a48792d8fc7224511913c38564ec; buvid_fp_plain=undefined; buvid_fp=0921a48792d8fc7224511913c38564ec; enable_feed_channel=ENABLE; bp_t_offset_19312722=1056340325913591808; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDU0NzkxMzUsImlhdCI6MTc0NTIxOTg3NSwicGx0IjotMX0.Kx7a97UmVXB0o_YqGZ87-EMcu2yZmAas6YrHJNPl7CU; bili_ticket_expires=1745479075; SESSDATA=3ee297aa%2C1760771937%2C4913e%2A41CjAHeVXpZ7MaoijPVa5RCcLwBySAFvb6wr7jDyI9rm_BU6s5VIlygiwIfiyMt79rSiMSVlBYLTRjNDI5Y1g2UkhiUWhVZlUyRXRPa2Q2T2l0VzRTbUMzRXAyeDBjZ3UyTmV4TTZnYnhiR1NqaTdhZ0dBUlJweGJzZ0w3Z1NEckRWZm5nc2FEYzZRIIEC; bili_jct=65035a97b6d4e9ea3dad5a5716cb3e0e; home_feed_column=5; b_lsid=10FCA7271_1966091BFE3; browser_resolution=1912-962; sid=4ydp0v5l; CURRENT_FNVAL=4048"
    }
    count_url = f'https://api.bilibili.com/x/v2/reply/count?type=1&oid={bv_to_av(bv)}'
    count_response = requests.get(count_url, headers=header)
    total_count = count_response.json()['data']['count']
    time.sleep(1)
    comments = []
    # print(bv_to_av(bv))
    for i in range(1, int(total_count / 20) + 1):
        url = f'https://api.bilibili.com/x/v2/reply?type=1&oid={bv_to_av(bv)}&pn={i}'
        print(url)
        response = requests.get(url, headers=header)
        data = response.json()['data']
        print(data)
        replies = data['replies']
        for reply in replies:
            username = reply['member']['uname']
            content = reply['content']['message'].strip('\n')
            timestamp = reply['ctime']
            local_time = time.localtime(timestamp)
            formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
            reply_content = {
                '用户': username,
                '评论内容': content,
                '评论时间': formatted_time
            }
            comments.append(reply_content)
        time.sleep(1)
    with open(f'./upload/comment/{bv}_评论.csv', 'w', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=['用户','评论内容','评论时间'])
        writer.writeheader()
        writer.writerows(comments)



if __name__ == '__main__':
    pinglun('BV1C95QzMEdC')
